package com.xiaoge.basedevlibrary.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * Created by yanshengli on 15-1-17.
 */
@SuppressLint("SimpleDateFormat")
public class StringUtils {

    private final static Pattern                       emailer       = Pattern
                                                                             .compile ("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static ThreadLocal<SimpleDateFormat> dateFormater  = new ThreadLocal<SimpleDateFormat> () {

                                                                         @Override
                                                                         protected SimpleDateFormat initialValue(){
                                                                             return new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
                                                                         }
                                                                     };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat> () {

                                                                         @Override
                                                                         protected SimpleDateFormat initialValue(){
                                                                             return new SimpleDateFormat ("yyyy-MM-dd");
                                                                         }
                                                                     };

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate){
        try {
            return dateFormater.get ().parse (sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate){

        Date time = toDate (sdate);

        if (time == null) { return "Unknown"; }
        String ftime = "";
        Calendar cal = Calendar.getInstance ();

        // 判断是否是同一天
        String curDate = dateFormater2.get ().format (cal.getTime ());
        String paramDate = dateFormater2.get ().format (time);
        if (curDate.equals (paramDate)) {
            int hour = (int) ((cal.getTimeInMillis () - time.getTime ()) / 3600000);
            if (hour == 0) ftime = Math.max ((cal.getTimeInMillis () - time.getTime ()) / 60000, 1) + "分钟前";
            else ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime () / 86400000;
        long ct = cal.getTimeInMillis () / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis () - time.getTime ()) / 3600000);
            if (hour == 0) ftime = Math.max ((cal.getTimeInMillis () - time.getTime ()) / 60000, 1) + "分钟前";
            else ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days < 31) {
            ftime = days + "天前";
        } else if (days >= 31 && days <= 2 * 31) {
            ftime = "一个月前";
        } else if (days > 2 * 31 && days <= 3 * 31) {
            ftime = "2个月前";
        } else if (days > 3 * 31 && days <= 4 * 31) {
            ftime = "3个月前";
        } else {
            ftime = dateFormater2.get ().format (time);
        }
        return ftime;
    }

    /**
     * 以友好的方式显示时间
     * @param date
     * @return
     */
    public static String friendly_time(Date date){
        SimpleDateFormat f = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        return friendly_time (f.format (date));
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate){
        boolean b = false;
        Date time = toDate (sdate);
        Date today = new Date ();
        if (time != null) {
            String nowDate = dateFormater2.get ().format (today);
            String timeDate = dateFormater2.get ().format (time);
            if (nowDate.equals (timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 返回long类型的今天的日期
     * @return
     */
    public static long getToday(){
        Calendar cal = Calendar.getInstance ();
        String curDate = dateFormater2.get ().format (cal.getTime ());
        curDate = curDate.replace ("-", "");
        return Long.parseLong (curDate);
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email){
        if (email == null || email.trim ().length () == 0) return false;
        return emailer.matcher (email).matches ();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str,int defValue){
        try {
            return Integer.parseInt (str);
        } catch (Exception e) {}
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj){
        if (obj == null) return 0;
        return toInt (obj.toString (), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj){
        try {
            return Long.parseLong (obj);
        } catch (Exception e) {}
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b){
        try {
            return Boolean.parseBoolean (b);
        } catch (Exception e) {}
        return false;
    }

    /**
     * 将一个InputStream流转换成字符串
     * @param is
     * @return
     */
    public static String toConvertString(InputStream is){
        StringBuffer res = new StringBuffer ();
        InputStreamReader isr = new InputStreamReader (is);
        BufferedReader read = new BufferedReader (isr);
        try {
            String line;
            line = read.readLine ();
            while (line != null) {
                res.append (line);
                line = read.readLine ();
            }
        } catch (IOException e) {
            e.printStackTrace ();
        } finally {
            try {
                if (null != isr) {
                    isr.close ();
                    isr.close ();
                }
                if (null != read) {
                    read.close ();
                    read = null;
                }
                if (null != is) {
                    is.close ();
                    is = null;
                }
            } catch (IOException e) {}
        }
        return res.toString ();
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str){
        if (str == null || str.trim ().length () == 0 || "".equals (str) || "NULL".equals (str)) { return true; }
        return false;
    }

    /**
     * 将字符串去空格
     * @param str
     * @param defaultStr
     * @return
     */
    public static String trimNull(String str,String defaultStr){
        if (isEmpty (str)) { return defaultStr; }
        return str.trim ();
    }

    /**
     * 将字符串去掉空格
     * @param str
     * @return
     */
    public static String trimNull(String str){
        return trimNull (str, "");
    }

    /**
     * 
    * @Title: formatMoney 
    * @Description: TODO(格式化金额) 
    * @param @param format
    * @param @param value
    * @param @return    
    * @return String    
    * @throws
     */
    public static String formatMoney(String format,Object value){
        if (TextUtils.isEmpty (format)) {
            return new DecimalFormat ("##,##0.00").format (value);
        } else {
            return String.format (format, new DecimalFormat ("##,##0.00").format (value));
        }
    }

    /**
     * 
    * @Title: formatMoney 
    * @Description: TODO(格式化金额) 
    * @param @param value
    * @param @return    
    * @return String    
    * @throws
     */
    public static String formatMoney(float value){
        try {
            return new DecimalFormat ("##,##0.00").format (value);
        } catch (Exception e) {
            return String.valueOf (value);
        }
    }

    /**
     * 
    * @Title: formatMoney 
    * @Description: TODO(格式化金额) 
    * @param @param format
    * @param @param value
    * @param @return    
    * @return String    
    * @throws
     */
    public static String formatMoney(String format,float value){
        return String.format (format, formatMoney (value));
    }
}
